//
//  PatterLockViewController.m
//  PatternLock
//
//  Created by Ryan on 13-5-9.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "PatterLockViewController.h"
#import "PatternLockPwdManager.h"
#import "NSString+MD5.h"
#import "GesturePwdViewController.h"
#import "NYMemberCenterDataManager.h"

#define kLessPassword       @"密码太短，最少4位，请重新绘制"
#define kDisaccordPassword  @"两次图案不一致，请重新绘制"
#define kInputPassword      @"绘制解锁图案"
#define kReInputPassword    @"请再次绘制解锁图案"
#define kErrorPassword      @"手势错误，请重新绘制"

#define kResetButtonForgetTitle     @"忘记手势？"
#define kResetButtonResetTitle      @"重新设置手势"

@interface PatterLockViewController ()

@property (nonatomic, copy) NSString *tempPassword;

@end

@implementation PatterLockViewController

@synthesize patternLockView;
@synthesize confirmContainView;
@synthesize promptLabel,resetButton;
@synthesize tempPassword;
@synthesize lockType;

- (IBAction)resetButtonClicked:(id)sender
{
    if(self.lockType == kUnlockType)
    {
        //解锁时忘记手势密码
        GesturePwdViewController *gpvc = [[GesturePwdViewController alloc] init];
        [self.navigationController pushViewController:gpvc animated:YES];
        [gpvc release];
    }
    else
    {
        //设置手势密码时重新设置
        self.tempPassword = nil;
        for(id v in self.confirmContainView.subviews)
        {
            if([v isKindOfClass:[UIImageView class]])
            {
                UIImageView *imgView = (UIImageView *)v;
                imgView.highlighted = NO;
            }
        }
        self.resetButton.hidden = YES;
        self.promptLabel.text = kInputPassword;
    }
}

- (void)setLockType:(LockType)lt
{
    lockType = lt;
    self.promptLabel.text = kInputPassword;
    if(lockType == kSetLockType)
    {
        self.resetButton.hidden = YES;
        self.confirmContainView.hidden = NO;
    }
    else
    {
        self.confirmContainView.hidden = YES;
    }
}

#pragma mark - Notification methods
- (void)hidePatternLockViewWithNotification:(NSNotification *)notification
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle:@"手势密码"];
    [self setLeftNaviItemWithTitle:nil imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hidePatternLockViewWithNotification:) name:kHidePatternLockViewNotification object:nil];
    
    self.patternLockView.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        self.view = nil;
        self.patternLockView = nil;
        self.confirmContainView = nil;
        self.resetButton = nil;
        self.promptLabel = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.patternLockView = nil;
    self.confirmContainView = nil;
    self.resetButton = nil;
    self.promptLabel = nil;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [tempPassword release];
    [resetButton release];
    [promptLabel release];
    [confirmContainView release];
    [patternLockView release];
    [super dealloc];
}

#pragma mark - RYPatternLockViewDelegate method
- (void)didPatternLockFinishedWithPassword:(NSString *)password
{
    //设置手势密码
    if(self.lockType == kSetLockType)
    {
        if(!self.tempPassword)
        {
            //第一次设置密码
            if(password.length < 4)
            {
                self.promptLabel.text = kLessPassword;
                return;
            }
            
            NSRange range = NSMakeRange(0, 1);
            for(int i = 0; i < password.length; i++)
            {
                range.location = i;
                NSString *subString = [password substringWithRange:range];
                NSInteger tag = [subString integerValue];
                UIImageView *imgView = (UIImageView *)[self.confirmContainView viewWithTag:tag];
                imgView.highlighted = YES;
            }
            self.promptLabel.text = kReInputPassword;
            self.tempPassword = password;
        }
        else
        {
            if(![self.tempPassword isEqualToString:password])
            {
                //第二次密码与第一次密码不一致
                self.promptLabel.text = kDisaccordPassword;
                [self.resetButton setTitle:kResetButtonResetTitle forState:UIControlStateNormal];
                self.resetButton.hidden = NO;
            }
            else
            {
                //密码设置成功 - 将密码发送到服务端
                [[PatternLockPwdManager sharedManager] saveGesturePassword:password];
//                [self dismissModalViewControllerAnimated:YES];
            }
        }
    }
    else
    {
        //解锁手势密码
        NSString *md5Pwd = [NSString md5HexDigest:password];
        if(![md5Pwd isEqualToString:[PatternLockPwdManager sharedManager].lockMember.gesture_password])
        {
            //解锁失败
            self.promptLabel.text = kErrorPassword;
            [self.resetButton setTitle:kResetButtonForgetTitle forState:UIControlStateNormal];
            self.resetButton.hidden = NO;
        }
        else
        {
            //解锁成功 - 保存已经解锁的状态，以后不用再次解锁
            NSMutableDictionary *dict = nil;
            if([[NSUserDefaults standardUserDefaults] objectForKey:kIsGestureAuthed])
            {
                dict = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] dictionaryForKey:kIsGestureAuthed]];
            }
            else
            {
                dict = [NSMutableDictionary dictionary];
            }
            [dict setObject:@"1" forKey:[NYMemberCenterDataManager sharedManager].loginMember.accountId];
            [[NSUserDefaults standardUserDefaults] setObject:dict forKey:kIsGestureAuthed];
            
            if(lockPage == kAccountProductPage)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:kShowAccountProsViewNotification object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:kHideMenuNotification object:nil];
            }
            else if(lockPage == kUserReminderPage)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:kShowMyReminderNotification object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:kHideMenuNotification object:nil];
            }
            else
            {
                
            }
            
            [self dismissModalViewControllerAnimated:YES];
        }
    }
}
@end
